const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const logger = require('../config/logger');

// 课程模型定义
const Course = sequelize.define('Course', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true,
    comment: '课程唯一标识'
  },
  
  // 基本信息
  title: {
    type: DataTypes.STRING(200),
    allowNull: false,
    validate: {
      len: [1, 200]
    },
    comment: '课程标题'
  },
  
  subtitle: {
    type: DataTypes.STRING(500),
    allowNull: true,
    comment: '课程副标题'
  },
  
  description: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '课程描述'
  },
  
  content: {
    type: DataTypes.TEXT('long'),
    allowNull: true,
    comment: '课程内容（富文本）'
  },
  
  // 分类和标签
  categoryId: {
    type: DataTypes.UUID,
    allowNull: true,
    comment: '课程分类ID'
  },
  
  tags: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: [],
    comment: '课程标签'
  },
  
  // 难度和级别
  level: {
    type: DataTypes.ENUM('beginner', 'intermediate', 'advanced', 'expert'),
    allowNull: false,
    defaultValue: 'beginner',
    comment: '课程难度级别'
  },
  
  // 媒体资源
  coverImage: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '课程封面图片URL'
  },
  
  videoUrl: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '课程视频URL'
  },
  
  videoDuration: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '视频时长（秒）'
  },
  
  audioUrl: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '课程音频URL'
  },
  
  audioDuration: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '音频时长（秒）'
  },
  
  attachments: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: [],
    comment: '课程附件列表'
  },
  
  // 教师信息
  teacherId: {
    type: DataTypes.UUID,
    allowNull: false,
    comment: '授课教师ID'
  },
  
  // 状态信息
  status: {
    type: DataTypes.ENUM('draft', 'published', 'archived', 'deleted'),
    allowNull: false,
    defaultValue: 'draft',
    comment: '课程状态'
  },
  
  publishedAt: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '发布时间'
  },
  
  // 学习相关
  estimatedDuration: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '预计学习时长（分钟）'
  },
  
  prerequisites: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: [],
    comment: '前置课程要求'
  },
  
  learningObjectives: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: [],
    comment: '学习目标'
  },
  
  // 价格信息
  price: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    defaultValue: 0.00,
    comment: '课程价格'
  },
  
  originalPrice: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    comment: '原价'
  },
  
  discountPrice: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    comment: '折扣价'
  },
  
  isFree: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false,
    comment: '是否免费'
  },
  
  // 统计信息
  viewCount: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '浏览次数'
  },
  
  enrollmentCount: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '报名人数'
  },
  
  completionCount: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '完成人数'
  },
  
  averageRating: {
    type: DataTypes.DECIMAL(3, 2),
    allowNull: false,
    defaultValue: 0.00,
    comment: '平均评分'
  },
  
  ratingCount: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '评分人数'
  },
  
  // 设置选项
  allowComments: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: true,
    comment: '是否允许评论'
  },
  
  allowRating: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: true,
    comment: '是否允许评分'
  },
  
  allowDownload: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false,
    comment: '是否允许下载'
  },
  
  requiresApproval: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false,
    comment: '是否需要审核'
  },
  
  // 时间限制
  enrollmentStartDate: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '报名开始时间'
  },
  
  enrollmentEndDate: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '报名结束时间'
  },
  
  studyStartDate: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '学习开始时间'
  },
  
  studyEndDate: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '学习结束时间'
  },
  
  // SEO相关
  seoTitle: {
    type: DataTypes.STRING(200),
    allowNull: true,
    comment: 'SEO标题'
  },
  
  seoDescription: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: 'SEO描述'
  },
  
  seoKeywords: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: 'SEO关键词'
  },
  
  // 扩展字段
  settings: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: {},
    comment: '课程设置'
  },
  
  metadata: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: {},
    comment: '扩展元数据'
  }
}, {
  tableName: 'courses',
  timestamps: true,
  paranoid: true, // 软删除
  indexes: []
});

// 实例方法
// 检查课程是否可以报名
Course.prototype.canEnroll = function() {
  const now = new Date();
  
  // 检查课程状态
  if (this.status !== 'published') {
    return { canEnroll: false, reason: '课程未发布' };
  }
  
  // 检查报名时间
  if (this.enrollmentStartDate && now < this.enrollmentStartDate) {
    return { canEnroll: false, reason: '报名尚未开始' };
  }
  
  if (this.enrollmentEndDate && now > this.enrollmentEndDate) {
    return { canEnroll: false, reason: '报名已结束' };
  }
  
  return { canEnroll: true };
};

// 检查课程是否可以学习
Course.prototype.canStudy = function() {
  const now = new Date();
  
  // 检查课程状态
  if (this.status !== 'published') {
    return { canStudy: false, reason: '课程未发布' };
  }
  
  // 检查学习时间
  if (this.studyStartDate && now < this.studyStartDate) {
    return { canStudy: false, reason: '学习尚未开始' };
  }
  
  if (this.studyEndDate && now > this.studyEndDate) {
    return { canStudy: false, reason: '学习已结束' };
  }
  
  return { canStudy: true };
};

// 获取课程进度
Course.prototype.getProgress = function(userId) {
  // 这里需要关联学习进度表
  // 暂时返回模拟数据
  return {
    totalLessons: 10,
    completedLessons: 5,
    progress: 50,
    lastStudyTime: new Date()
  };
};

// 增加浏览次数
Course.prototype.incrementViewCount = async function() {
  return this.increment('viewCount');
};

// 增加报名人数
Course.prototype.incrementEnrollmentCount = async function() {
  return this.increment('enrollmentCount');
};

// 减少报名人数
Course.prototype.decrementEnrollmentCount = async function() {
  return this.decrement('enrollmentCount');
};

// 增加完成人数
Course.prototype.incrementCompletionCount = async function() {
  return this.increment('completionCount');
};

// 更新评分
Course.prototype.updateRating = async function(newRating) {
  const totalRating = this.averageRating * this.ratingCount + newRating;
  const newRatingCount = this.ratingCount + 1;
  const newAverageRating = totalRating / newRatingCount;
  
  return this.update({
    averageRating: Math.round(newAverageRating * 100) / 100,
    ratingCount: newRatingCount
  });
};

// 发布课程
Course.prototype.publish = async function() {
  return this.update({
    status: 'published',
    publishedAt: new Date()
  });
};

// 归档课程
Course.prototype.archive = async function() {
  return this.update({
    status: 'archived'
  });
};

// 获取课程统计信息
Course.prototype.getStatistics = function() {
  return {
    viewCount: this.viewCount,
    enrollmentCount: this.enrollmentCount,
    completionCount: this.completionCount,
    completionRate: this.enrollmentCount > 0 ? 
      Math.round((this.completionCount / this.enrollmentCount) * 100) : 0,
    averageRating: this.averageRating,
    ratingCount: this.ratingCount
  };
};

// 类方法
// 根据分类查找课程
Course.findByCategory = function(categoryId, options = {}) {
  return this.findAll({
    where: {
      categoryId,
      status: 'published'
    },
    ...options
  });
};

// 根据教师查找课程
Course.findByTeacher = function(teacherId, options = {}) {
  return this.findAll({
    where: {
      teacherId
    },
    ...options
  });
};

// 搜索课程
Course.search = function(keyword, options = {}) {
  return this.findAll({
    where: {
      [sequelize.Sequelize.Op.or]: [
        {
          title: {
            [sequelize.Sequelize.Op.like]: `%${keyword}%`
          }
        },
        {
          description: {
            [sequelize.Sequelize.Op.like]: `%${keyword}%`
          }
        },
        {
          tags: {
            [sequelize.Sequelize.Op.like]: `%${keyword}%`
          }
        }
      ],
      status: 'published'
    },
    ...options
  });
};

// 获取热门课程
Course.getPopular = function(limit = 10) {
  return this.findAll({
    where: {
      status: 'published'
    },
    order: [
      ['enrollmentCount', 'DESC'],
      ['averageRating', 'DESC']
    ],
    limit
  });
};

// 获取最新课程
Course.getLatest = function(limit = 10) {
  return this.findAll({
    where: {
      status: 'published'
    },
    order: [['publishedAt', 'DESC']],
    limit
  });
};

// 获取推荐课程
Course.getRecommended = function(userId, limit = 10) {
  // 这里可以实现推荐算法
  // 暂时返回高评分课程
  return this.findAll({
    where: {
      status: 'published',
      averageRating: {
        [sequelize.Sequelize.Op.gte]: 4.0
      }
    },
    order: [['averageRating', 'DESC']],
    limit
  });
};

// 获取免费课程
Course.getFree = function(options = {}) {
  return this.findAll({
    where: {
      status: 'published',
      isFree: true
    },
    ...options
  });
};

// 根据难度级别查找课程
Course.findByLevel = function(level, options = {}) {
  return this.findAll({
    where: {
      level,
      status: 'published'
    },
    ...options
  });
};

// 钩子函数
// 发布时设置发布时间
Course.beforeUpdate((course) => {
  if (course.changed('status') && course.status === 'published' && !course.publishedAt) {
    course.publishedAt = new Date();
  }
});

// 记录课程创建日志
Course.afterCreate((course) => {
  logger.business('课程创建', {
    courseId: course.id,
    title: course.title,
    teacherId: course.teacherId,
    status: course.status
  });
});

// 记录课程更新日志
Course.afterUpdate((course) => {
  const changes = course.changed();
  if (changes && changes.length > 0) {
    logger.business('课程更新', {
      courseId: course.id,
      changes: changes.filter(field => !['updatedAt', 'viewCount'].includes(field))
    });
  }
});

// 记录课程删除日志
Course.afterDestroy((course) => {
  logger.business('课程删除', {
    courseId: course.id,
    title: course.title,
    teacherId: course.teacherId
  });
});

module.exports = Course;